package com.mp.approvalreq.servlet.comment;


import com.alibaba.fastjson.JSONObject;
import com.mp.approvalreq.entity.Comment;
import com.mp.approvalreq.service.ApprovalCommentServicePrx;
import com.mp.approvalreq.servlet.AbstractServlet;
import com.mp.approvalreq.util.ServiceUtils;
import com.mp.user.entity.User;
import com.plusmoney.exception.ParameterException;
import com.plusmoney.util.ParameterUtils;
import com.qq.tars.client.util.ServantUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 撤销评论(测试Ok)
 */
@WebServlet("/cancelComment")
public class CancelComment extends AbstractServlet {
    private static final Logger logger = LoggerFactory.getLogger(CancelComment.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        try {
            User user = ServiceUtils.getUserInfo(req);

            Comment comment = ParameterUtils.getObjectParameter(req, Comment.class);
            check(comment);

            ApprovalCommentServicePrx commentServicePrx = ServantUtils.getObject(ApprovalCommentServicePrx.class);
            int isCancel = commentServicePrx.cancelComment(comment, user);

            returnResult(resp, isCancel);
        } catch (Throwable e) {
            onThrowable(req, resp, e);
        }
    }

    private void returnResult(HttpServletResponse resp, int isCancel) throws Throwable {
        JSONObject jsonObject = new JSONObject();
        switch (isCancel) {
            case 0:
                jsonObject.put("respCode", "444");
                jsonObject.put("respDesc", "评论不存在或者已被撤回");
                break;

            case 1:
                jsonObject.put("respCode", "000");
                jsonObject.put("respDesc", "撤回成功");
                break;

            case 2:
                jsonObject.put("respCode", "111");
                jsonObject.put("respDesc", "已有新评论，不能撤回");
                break;

            case 3:
                jsonObject.put("respCode", "222");
                jsonObject.put("respDesc", "评论已超过2分钟，不能撤回");
                break;

            default:
                break;
        }
        logger.info("审批撤回评论返回:{}", jsonObject.toJSONString());

        resp.setHeader("Content-Type", "application/json;charset = utf-8");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().write(jsonObject.toJSONString());
        resp.flushBuffer();
    }


    private void check(Comment comment) {
        if (comment.getId() <= 0) {
            throw new ParameterException("参数格式错误");
        }
    }

}
